$(document).ready(function(){
    $('#tabs').tabs();
    if ($('#diatodo').attr('checked')){
        $('#hrinicio').hide();
        $('#hrfim').hide();
    }
    //$('#vezes').attr('disabled',true);
    //$('#dias').attr('disabled',true);
    $('#diatodo').click(function(){
        if ($('#diatodo').attr('checked')){
            //$('#hrinicio').attr('disabled',true);
            //$('#hrfim').attr('disabled',true);
            $('#hrinicio').hide();
            $('#hrfim').hide();
        }else{
            //$('#hrinicio').removeAttr('disabled');
            //$('#hrfim').removeAttr('disabled');
            $('#hrinicio').show();
            $('#hrfim').show();
        }
    });
    $('#periodicidade').change(function(){
        alert($('#periodicidade option:selected').val());
        if ($('#periodicidade option:selected').val()!=''){
            $('#vezes').removeAttr('disabled');
            $('#dias').removeAttr('disabled');
        }else{
            $('#vezes').attr('disabled',true);
            $('#dias').attr('disabled',true);
        }
    });
    $("#dtinicio").datepicker({
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dateFormat: 'dd/mm/yy',
        constrainInput: true,
        selectOtherMonths: true,
        showWeek: true,
        weekHeader: 'S',
        formatDate: 'dd/mm/yy'
    });
    $("#dtfim").datepicker({
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dateFormat: 'dd/mm/yy',
        constrainInput: true,
        selectOtherMonths: true,
        showWeek: true,
        weekHeader: 'S',
        formatDate: 'dd/mm/yy'
    });
    $("#dttermino").datepicker({
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
        dateFormat: 'dd/mm/yy',
        constrainInput: true,
        selectOtherMonths: true,
        showWeek: true,
        weekHeader: 'S',
        formatDate: 'dd/mm/yy'
    });

    $('#ac_colaborador').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/colaborador/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    response($.map(data.colaboradores, function(item) {
                        return {
                            label: item.nome,
                            value: item.codusu
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#ac_colaborador').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#colaborador_id').val('');
        },
        select: function(event,ui){
            $('#colaborador_id').val(ui.item.value);
            $('#ac_colaborador').val(ui.item.label);
            if ($('#colaborador_id').val()!=''){
                $.ajax({
                    url: "/contato/index",
                    processData: false,
                    data: 'cliente_id='+$('#colaborador_id').val(),
                    beforeSend: function (){
                        var pos = $('#ac_colaborador').position();
                        var width = $('#ac_colaborador').width();
                        $("#ajax-ldr").css( {
                            "left": (pos.left+width+5) + "px",
                            "top":pos.top + "px"
                        } ).fadeIn('fast');

                    },
                    success: function(msg){
                        $('#contato_id option').remove();
                        $('#contato_id').append("<option value=''>Selecione o Contato...</option>")
                        for (i = 0; i < msg.length; i++) {
                            $('#contato_id').append("<option value='"+msg[i].idcontato+"'>"+msg[i].dsnome+"</option>")
                        }
                        $('#ajax-ldr').fadeOut('fast');
                    }
                });
            }
            return false;
        },
        minLength: 3,
        delay: 300
    });
    $('#ac_funcionario').autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/funcionarios/index",
                type: "POST",
                datatype: "json",
                data: {
                    q: request.term
                },
                success: function(data) {
                    //alert(data);
                    response($.map(data, function(item) {
                        return {
                            label: item.nome,
                            value: item.id
                        }
                    }))
                }
            })
        },
        focus: function(event,ui){
            $('#usuario_id').val(ui.item.label);
            return false;
        },
        open: function(event,ui) {
            $('#usuario_id').val('');
        },
        select: function(event,ui){
            //alert(ui.item.label);
            $('#usuario_id').val(ui.item.value);
            //alert($('#usuario_id').val());
            $('#ac_funcionario').val(ui.item.label);
            return false;
        },
        minChars : 3
    });

    $('#submit').button().click(function(){
        $('form').submit();
    });
    $('textarea.tinymce').tinymce({
        // Location of TinyMCE script
        script_url : '/js/tiny_mce/tiny_mce.js',

        // General options
        theme : "advanced",
        plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
        theme_advanced_buttons2 : '',
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        content_css : "css/content.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js",

        // Replace values for the template plugin
        template_replace_values : {
            username : "Some User",
            staffid : "991234"
        }
    });

    function atualiza(){
        var aux  = "";
        var aux2 = "";
        if ($('#dom').attr('checked')) aux2 = ' cada Domingo';
        if ($('#seg').attr('checked')) aux2 += ((aux2 == "") ? " cada Segunda" : ", segunda");
        if ($('#ter').attr('checked')) aux2 += ((aux2 == "") ? " cada Ter�a" : ", ter�a");
        if ($('#qua').attr('checked')) aux2 += ((aux2 == "") ? " cada Quarta" : ", quarta");
        if ($('#qui').attr('checked')) aux2 += ((aux2 == "") ? " cada Quinta" : ", quinta");
        if ($('#sex').attr('checked')) aux2 += ((aux2 == "") ? " cada Sexta" : ", sexta");
        if ($('#sab').attr('checked')) aux2 += ((aux2 == "") ? " cada S�bado" : ", s�bado");
        if ($('#frequencia option:selected').val()=='Semanal'){
            if ($('#intervalo').val()==1){
                aux = $('#frequencia option:selected').val()+': ';
            }else{
                aux = 'a cada '+$('#intervalo').val()+' Semanas';
            }
            aux += aux2;
        }
        else if($('#frequencia option:selected').val()=='Mensal'){
            if ($('#intervalo').val()==1){
                aux = $('#frequencia option:selected').val()+': ';
            }else{
                aux = 'a cada '+$('#intervalo').val()+' Meses';
            }
        }
        $('#resumo').html('<b>'+aux+'</b>');
    }

    $('#frequencia').change(function(){
        atualiza();
    });
    $('.diasemana').change(function(){
        atualiza();
    });
    $('#intervalo').change(function(){
       atualiza();
    });
    $("#dialog").dialog({
        dialogClass: 'alert',
        draggable: true,
        modal: true,
        title: 'Repetir',
        resizable: true,
        show: 'fadeIn',
        autoSize: true,
        autoOpen: false,
        minWidth: 400,
        width: 400,
        close: function(event, ui) {
            //$('#descricao').val(''); $('#nome_rotina').val('');
            //$('#data').val(''); $('#controller').val('');
            //$('#action').val(''); $('#horas').val('');
            //$('#minutos').val(''); $('#rotina_id').val('');
            //$('.error').hide();
            $('#intervalo').val('');
            $('#repetir').attr('checked', false);
        },
        buttons: {
            'Conclu�do':function(){
                $.ajax({
                    url: "/tasks/trabalhar",
                    processData: false,
                    data: 'tarefa_id='+$('#tarefa_id').val()+'&descricao='+escape($('#descricao').val())+'&user_id='+$('#user_id').val()+
                    '&rotina_id='+$('#rotina_id').val()+'&horas='+$('#horas').val()+'&minutos='+$('#minutos').val()+
                    '&data='+$('#data').val()+'&controller='+$('#controller').val()+'&action='+$('#action').val()+
                    '&nome_rotina='+$('#nome_rotina').val()+'&model='+$('#model').val()+'&views='+$('#views').val(),
                    beforeSend: function (){
                        //                        var pos = $("#trab_"+tarefa).position();
                        //                       var width = $("#trab_"+tarefa).width();
                        //                      $("#ajax-ldr").css( {
                        //                         "left": (pos.left+width+5) + "px",
                        //                        "top":pos.top + "px"
                        //                   } ).fadeIn('fast');
                        $("#wait").fadeIn('fast').html('Fechando Tarefa...');
                    },
                    success: function(msg){
                        $('#ajax-ldr').fadeOut('fast');
                        $("#wait").fadeOut('fast');
                        if (msg==true){
                            $('#dialog').dialog('close');
                            $('#descrical').val('');$('#nome_rotina').val('');
                            $('#data').val('');$('#controller').val('');
                            $('#action').val('');$('#horas').val('');
                            $('#minutos').val('');$('#rotina_id').val('');
                            $('.error').hide();
                        }
                        else{
                            $('.error').hide();
                            $.each(msg,function(key,value){
                                showError(key, value);
                            });
                        }
                    }
                });
            },
            'Cancelar': function(){
                $('#dialog').dialog('close');
                $('#dialog').dialog('close');
                $('#descricao').val('');$('#nome_rotina').val('');
                $('#data').val('');$('#controller').val('');
                $('#action').val('');$('#horas').val('');
                $('#minutos').val('');$('#rotina_id').val('');
                $('.error').hide();
                return false;
            }
        }
    });
    $('#repetir').click(function(){
        if ($('#repetir').attr('checked')){
            $('#dialog').dialog('open');
        }
    });
});